/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lepu.app.fun.chat.util;

import java.io.File;
import java.util.HashMap;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.core.lib.core.HttpRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.secure.EncodeMD5;
import com.lepu.app.fun.chat.bean.ChatMessage;
import com.lepu.app.fun.chat.core.ChatManager;
import com.lepu.pasm.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;

public class VoicePlayClickListener implements View.OnClickListener {

	ChatMessage message;
	ImageView voiceIconView;
	ImageView iv_read_status;

	private AnimationDrawable voiceAnimation = null;
	MediaPlayer mediaPlayer = null;
	Context context;

	public static boolean isPlaying = false;
	public static VoicePlayClickListener currentPlayListener = null;
	static ChatMessage currentMessage = null;
	private HashMap<String,String> mPlayMaps = new HashMap<String,String>();
	private String mPlayPosition = "0";

	ListView mListView;

	/**
	 *
	 * @param message
	 * @param voiceImageView
	 * @param read_status
	 * @param context
	 */
	public VoicePlayClickListener(ChatMessage message, ImageView voiceImageView,
			ImageView read_status, Context context,int position,ListView listView) {
		this.message = message;
		voiceIconView = voiceImageView;
		iv_read_status = read_status;
		this.context = context;

		mPlayPosition = String.valueOf(position);
		mListView = listView;

		if (voiceAnimation != null) {
			voiceAnimation.stop();
		}

		if (mPlayMaps.containsKey(mPlayPosition)) {
			showAnimation();
		}
	}

	public void stopPlayVoice() {
		if(voiceAnimation != null){
			voiceAnimation.stop();
		}

		if(message != null){
			if (message.getDirection() == Constants.Chat.CHAT_DIRECTION_RECEIVE) {
				voiceIconView.setImageResource(R.drawable.chatfrom_voice_playing);
			} else {
				voiceIconView.setImageResource(R.drawable.chatto_voice_playing);
			}
		}

		// stop play voice
		stopVoice();
		isPlaying = false;
		currentPlayListener = null;
	}

	public void stopVoice()
	{
		if (mediaPlayer != null) {
			try {
				mediaPlayer.stop();
				mediaPlayer.release();
			}catch (Exception e){
			}
			mediaPlayer = null;
		}

		if(mPlayMaps.size() > 0){
			mPlayMaps.remove(mPlayPosition);
		}
	}

	public void setSpeakerphoneOn(boolean flag)
	{
		if(mediaPlayer == null){
			return;
		}

		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);

		if(flag)
		{
			//audioManager.setSpeakerphoneOn(true);
			audioManager.setMode(AudioManager.MODE_NORMAL);
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
		}else{
			//audioManager.setSpeakerphoneOn(false);// 关闭扬声器
			// 把声音设定成Earpiece（听筒）出来，设定为正在通话中
			audioManager.setMode(AudioManager.MODE_IN_CALL);
			//mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
		}
	}

	public void playVoice(String filePath) {
		if (!(new File(filePath).exists())) {
			return;
		}
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);

		mediaPlayer = new MediaPlayer();
//		setSpeakerphoneOn(true);

		try {
			mediaPlayer.setAudioStreamType(AudioManager.MODE_NORMAL);
			mediaPlayer.setDataSource(filePath);
			mediaPlayer.prepare();
			mediaPlayer
					.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

						@Override
						public void onCompletion(MediaPlayer mp) {
							// TODO Auto-generated method stub
							mediaPlayer.release();
							mediaPlayer = null;
							stopPlayVoice(); // stop animation
						}

					});
			isPlaying = true;
			currentPlayListener = this;
			currentMessage = message;
			mediaPlayer.start();
			showAnimation();

			mPlayMaps.put(mPlayPosition, "");
			try {
				// 如果是接收的消息
				if (!message.isRead()
						&& message.getDirection() == Constants.Chat.CHAT_DIRECTION_RECEIVE) {
					message.setRead(true);
					if (iv_read_status != null
							&& iv_read_status.getVisibility() == View.VISIBLE) {
						// 隐藏自己未播放这条语音消息的标志
						iv_read_status.setVisibility(View.INVISIBLE);
						ChatManager.getInstance().resetYuYinReadStateMessage(
								message.getMessageId());
					}
					// 告知对方已读这条消息
				}
			} catch (Exception e) {
				message.setRead(false);
			}
		} catch (Exception e) {
		}
	}

	// show the voice playing animation
	private void showAnimation() {
		// play voice, and start animation
		if (message.getDirection() == Constants.Chat.CHAT_DIRECTION_RECEIVE) {
			voiceIconView.setImageResource(R.anim.voice_from_icon);
		} else {
			voiceIconView.setImageResource(R.anim.voice_to_icon);
		}
		voiceAnimation = (AnimationDrawable) voiceIconView.getDrawable();
		voiceAnimation.start();
	}

	@Override
	public void onClick(View v) {

		if (isPlaying) {
			currentPlayListener.stopPlayVoice();
			if (currentMessage != null
					&& currentMessage.hashCode() == message.hashCode()) {
				currentMessage = null;
				return;
			}
		}

		if(message.getDirection() == Constants.Chat.CHAT_DIRECTION_RECEIVE){
			String downloadUrl = message.getMedia().getObjectId();
			String fileName = EncodeMD5.getMd5(downloadUrl);
			String filePath = SdLocal.getChatVoicePath(MyApplication.getInstance(), LoginUtil.getUserId(), fileName);
			File file = new File(filePath);

			if (file.exists() && file.isFile()) {
				playVoice(filePath);
			} else {
				//下载地址
				if (!TextUtils.isEmpty(downloadUrl)) {
					ProgressBar progressBar = (ProgressBar) mListView.findViewWithTag(String.format("%s", downloadUrl));
					if (progressBar != null) {
						progressBar.setVisibility(View.VISIBLE);
						downloadFile(downloadUrl);
					}
				}
			}
		}else{
			String filePath = message.getMedia().getFullName();
			File file = new File(filePath);
			if (file.exists() && file.isFile()) {
				playVoice(filePath);
			}
		}

	}

	private void downloadFile(final String ServerUrl) {
		final String fileName = EncodeMD5.getMd5(ServerUrl);
		final String ServerPath = SdLocal.getChatVoicePath(context, LoginUtil.getUserId(), fileName);

		new Thread(new Runnable() {
			@Override
			public void run() {
				HttpRequest.downloadFileBy(ServerUrl, ServerPath, new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);

						Message msg = mHandler.obtainMessage();
						msg.what = 10;
						msg.obj = ServerUrl;
						mHandler.sendMessage(msg);
					}

					@Override
					public void callBackFail(Object obj) {
						super.callBackFail(obj);
						Message msg = mHandler.obtainMessage();
						msg.what = 11;
						msg.obj = ServerUrl;
						mHandler.sendMessage(msg);
					}
				});
			}
		}).start();
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 10:
				case 11:

					String url = (String) msg.obj;

					ProgressBar progressBar = (ProgressBar) mListView.findViewWithTag(String.format("%s", url));
					if (progressBar != null) {
						progressBar.setVisibility(View.GONE);
					}

					ImageView receiveContentTipImageView = (ImageView) mListView.findViewWithTag(String.format("%s_tip", url));
					if(msg.what == 11){
						UIHelper.showToast(context, "加载失败，请检查网络");
						if (receiveContentTipImageView != null) {
							receiveContentTipImageView.setVisibility(View.VISIBLE);
						}
					}else{
						if (receiveContentTipImageView != null) {
							receiveContentTipImageView.setVisibility(View.GONE);
						}
					}
					break;

				default:
					break;
			}
		}
	};


	interface OnVoiceStopListener {
		void onStop();

		void onStart();
	}

}